package com.report;

import com.report.service.ReportRuleService;
import com.schedule.ReportGenerateScheduleManage;
import com.schedule.domain.ReportRule;
import com.schedule.domain.ReportRuleTask;
import com.schedule.domain.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManagerFactory;
import java.util.Iterator;
import java.util.List;

/**
 * @Auther zhangdajun
 * @CreateDate 2018/11/3 11 51
 * @Describe
 */
@Component
public class CheckTask {

    private boolean isFirst = true;

    @Autowired
    ReportRuleService reportRuleService;

    @Autowired
    EntityManagerFactory entityManagerFactory;
    @Autowired
    ReportGenerateScheduleManage reportGenerateScheduleManage;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void process(){
        Iterator<Template> templateIterator;
        // 每分钟执行一次检查
        if(isFirst){
            templateIterator = reportRuleService.loadAll();
            isFirst = false;
        }else{
            templateIterator = reportRuleService.loadLastOneMinuteReportRule();
        }
        templateIterator.forEachRemaining(reportRule -> {
            // 获取该规则下关联的任务
            List<ReportRuleTask> reportRuleTasks = reportRuleService.loadAllByRuleId(reportRule.getId());
            // 获取任务数据
            reportGenerateScheduleManage.edit(reportRule,reportRuleTasks);
        });

    }
}
